package by.averianov.discounta.webapp.page.tabs;

import java.util.Iterator;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.wicket.Page;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.averianov.discounta.datamodel.UserProfile;
import by.averianov.discounta.datamodel.UserProfile_;
import by.averianov.discounta.services.UserService;
import by.averianov.discounta.webapp.page.administrator.Administrator;
import by.averianov.discounta.webapp.page.create.CreateUser;
import by.averianov.discounta.webapp.page.table.Row;

public class TabUser extends Panel {

	private static final Logger LOGGER = LoggerFactory.getLogger(TabShop.class);

	protected Long selectId;
	private String currentId;
	
	@Inject
	private UserService userService;
	 
    public TabUser(String id,  Long selectId, String currentId) {
    	super(id);
    	this.selectId = selectId;
    	this.currentId = currentId;
	}
    
	private class UserProfileDataProvider extends SortableDataProvider<UserProfile, SingularAttribute<UserProfile, ?>> {

		public UserProfileDataProvider() {
			super();
			setSort(UserProfile_.id, SortOrder.ASCENDING);
		}
	
		@Override
		public Iterator<? extends UserProfile> iterator(long first, long count) {
	
			SingularAttribute<UserProfile, ?> sortParam = getSort().getProperty();
			SortOrder propertySortOrder = getSortState().getPropertySortOrder(sortParam);
			boolean ascending = SortOrder.ASCENDING.equals(propertySortOrder);
			return userService.getAllUserProfile(sortParam, ascending, (int) first, (int) count).iterator();
		}
	
		@Override
		public long size() {
			return userService.getUserCount();
		}
	
		@Override
		public IModel<UserProfile> model(UserProfile userProfile) {
			return new CompoundPropertyModel<UserProfile>(userProfile);
		}
	}
    
    @Override
	protected void onInitialize() {
		super.onInitialize();
		
		Link linkAdd = new Link("linkAdd") {
			@Override
			public void onClick() {
				setResponsePage(new CreateUser(null, null, new PageCreator() {

					@Override
					public Page createPage() {
						return new Administrator(3, 0L);
					}
				}));
				LOGGER.debug("Add Row");
			}
		};
		linkAdd.add(new Label("labelAdd", getButtonAdd()));
		add(linkAdd);

		Link linkChange = new Link("linkChange") {
			@Override
			public void onClick() {				
				if(selectId == null) {
					selectId = 0L;
				}
				setResponsePage(new CreateUser(userService.getUserAccount(selectId), userService.getUserProfile(selectId), new PageCreator() {

					@Override
					public Page createPage() {
						return new Administrator(3, selectId);
					}
				}));
				LOGGER.debug("Change Row");
			}
		};
		linkChange.add(new Label("labelChange", getButtonChange()));
		add(linkChange);
		
		Link linkDel = new Link("linkDel") {
			@Override
			public void onClick() {

				Administrator page = new Administrator(3, 0L);				
				if(selectId == 0) {
					page.error("Null row selected");
					setResponsePage(page);
				} else {
					userService.removeUser(selectId);
					LOGGER.debug("Delete Row");					
				}
				setResponsePage(page);
			}
		};
		linkDel.add(new Label("labelDel", getButtonDel()));
		add(linkDel);
		
		
		setOutputMarkupId(true);
    	UserProfileDataProvider userProfileDataProvider = new UserProfileDataProvider();

    	/*add(new AjaxLink<Void>("remove-ajax") {
            @Override
            public void onClick(AjaxRequestTarget target) {
            	LOGGER.info("Ajax onClick");
            	userService.removeUser(1L);
                target.add(TabUser.this);
                //target.add(TabbedPanelPage.this.get(0));
            	
            }

		});*/
    	
		final WebMarkupContainer tableBody = new WebMarkupContainer("wrapper-body") {
			@Override
			protected void onBeforeRender() {
				super.onBeforeRender();
			}
		};
	    	
		tableBody.setOutputMarkupId(true);
		add(tableBody);
			
		DataView<UserProfile> dataView = new DataView<UserProfile>("list", userProfileDataProvider, 15) {
						
			@Override
			protected void populateItem(final Item<UserProfile> item) {
				final UserProfile userProfile = item.getModelObject();				
				Boolean isSelected = false;
				
				if(selectId == userProfile.getId()) {
					isSelected = true;
				}
				
				item.add(new Row("row", userProfile, isSelected, currentId));
				item.setVisible(true);
			}
		};
	
		tableBody.add(dataView);
	
		add(new PagingNavigator("paging", dataView));
	
		add(new OrderByBorder<SingularAttribute<UserProfile, ?>>("sortById", UserProfile_.id, userProfileDataProvider));
		add(new OrderByBorder<SingularAttribute<UserProfile, ?>>("sortByUserFirstName", UserProfile_.userFirstName, userProfileDataProvider));
		add(new OrderByBorder<SingularAttribute<UserProfile, ?>>("sortByUserLastName", UserProfile_.userLastName, userProfileDataProvider));
		add(new OrderByBorder<SingularAttribute<UserProfile, ?>>("sortByUserDateCreated", UserProfile_.userDateCreated, userProfileDataProvider));
		add(new OrderByBorder<SingularAttribute<UserProfile, ?>>("sortByPhoneNumber", UserProfile_.phoneNumber, userProfileDataProvider));
		add(new OrderByBorder<SingularAttribute<UserProfile, ?>>("sortByAccessGroup", UserProfile_.accessGroup, userProfileDataProvider));	
		
	}
    

	protected IModel<String> getButtonAdd() {
		return new ResourceModel("p.button.add");
	}
	
	protected IModel<String> getButtonChange() {
		return new ResourceModel("p.button.change");
	}

	protected IModel<String> getButtonDel() {
		return new ResourceModel("p.button.del");
	}
	
	public String getPageTitle() {
        return super.getId();
    }
	 
}
